/*
 * Copyright (c) 2018. J4dream Created.
 */

package com.j4dream.property.job;

import com.google.common.collect.Lists;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DefaultFieldSet;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader;
import org.springframework.validation.BindException;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
public class CsvItemReader extends AbstractItemCountingItemStreamItemReader {

    private CSVParser csvParser;

    private Iterator<CSVRecord> iterator;

    @Setter
    private FieldSetMapper fieldSetMapper;

    public CsvItemReader(List<String> column) {
        setFieldSetMapper(new CSVFiledSetMapper(column));
    }

    @Override
    protected Object doRead() throws Exception {
        log.info("do read");
        if (iterator.hasNext()) {
            CSVRecord record = iterator.next();
            ArrayList<String> values = Lists.newArrayList(record.iterator());
            FieldSet fs = new DefaultFieldSet(values.toArray(new String[values.size()]));
            return fieldSetMapper.mapFieldSet(fs);
            //log.info(values.toString());
            // return values;
        } else {
            return null;
        }
    }

    @Override
    protected void doOpen() throws Exception {
        log.info("do open");
        this.csvParser = CSVFormat.DEFAULT.parse(new FileReader("/Users/dream/Desktop/bar.csv"));
        this.iterator = this.csvParser.iterator();
    }

    @Override
    protected void doClose() throws Exception {
        this.csvParser.close();
    }

    private static class CSVFiledSetMapper implements FieldSetMapper {

        private final List<String> column;

        public CSVFiledSetMapper(List<String> column) {
            this.column = column;
        }

        @Override
        public Object mapFieldSet(FieldSet fieldSet) throws BindException {
            return null;
        }
    }
}
